import React, { useState, useEffect } from 'react';
import {
  StyleSheet,
  View,
  Text,
  Switch,
  TouchableOpacity,
  ScrollView,
  Alert,
  Modal,
  TextInput,
} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Ionicons } from '@expo/vector-icons';
import { UserSettings } from '../types';
import { useTheme, ThemeType } from '../contexts/ThemeContext';

const DEFAULT_SETTINGS: UserSettings = {
  theme: 'system',
  defaultPomodoroSettings: {
    workDuration: 25,
    breakDuration: 5,
    longBreakDuration: 15,
    longBreakInterval: 4,
  },
  notifications: true,
  soundEnabled: true,
};

const SettingsScreen: React.FC = () => {
  const { theme, setTheme, colors } = useTheme();
  const [settings, setSettings] = useState<UserSettings>(DEFAULT_SETTINGS);
  const [showPomodoroModal, setShowPomodoroModal] = useState(false);
  const [tempPomodoroSettings, setTempPomodoroSettings] = useState(DEFAULT_SETTINGS.defaultPomodoroSettings);

  useEffect(() => {
    loadSettings();
  }, []);

  const loadSettings = async () => {
    try {
      const savedSettings = await AsyncStorage.getItem('userSettings');
      if (savedSettings) {
        setSettings(JSON.parse(savedSettings));
      }
    } catch (error) {
      console.error('加载设置失败:', error);
    }
  };

  const saveSettings = async (newSettings: UserSettings) => {
    try {
      await AsyncStorage.setItem('userSettings', JSON.stringify(newSettings));
      setSettings(newSettings);
    } catch (error) {
      Alert.alert('错误', '保存设置失败');
    }
  };

  const updateTheme = (newTheme: ThemeType) => {
    setTheme(newTheme);
    saveSettings({ ...settings, theme: newTheme });
  };

  const toggleNotifications = () => {
    saveSettings({ ...settings, notifications: !settings.notifications });
  };

  const toggleSound = () => {
    saveSettings({ ...settings, soundEnabled: !settings.soundEnabled });
  };

  const savePomodoroSettings = () => {
    saveSettings({
      ...settings,
      defaultPomodoroSettings: tempPomodoroSettings,
    });
    setShowPomodoroModal(false);
  };

  return (
    <ScrollView style={[styles.container, { backgroundColor: colors.background }]}>
      <View style={[styles.section, { backgroundColor: colors.card }]}>
        <Text style={[styles.sectionTitle, { color: colors.text }]}>主题设置</Text>
        <View style={styles.themeButtons}>
          {(['light', 'dark', 'system'] as const).map((themeOption) => (
            <TouchableOpacity
              key={themeOption}
              style={[
                styles.themeButton,
                { backgroundColor: colors.border },
                theme === themeOption && { backgroundColor: colors.primary },
              ]}
              onPress={() => updateTheme(themeOption)}
            >
              <Text
                style={[
                  styles.themeButtonText,
                  { color: colors.textSecondary },
                  theme === themeOption && { color: colors.card },
                ]}
              >
                {themeOption === 'light' ? '浅色'
                  : themeOption === 'dark' ? '深色'
                  : '跟随系统'}
              </Text>
            </TouchableOpacity>
          ))}
        </View>
      </View>

      <View style={[styles.section, { backgroundColor: colors.card }]}>
        <Text style={[styles.sectionTitle, { color: colors.text }]}>番茄钟设置</Text>
        <TouchableOpacity
          style={styles.settingItem}
          onPress={() => {
            setTempPomodoroSettings(settings.defaultPomodoroSettings);
            setShowPomodoroModal(true);
          }}
        >
          <Text style={[styles.settingLabel, { color: colors.text }]}>默认时长设置</Text>
          <Text style={[styles.settingValue, { color: colors.textSecondary }]}>
            {settings.defaultPomodoroSettings.workDuration}分钟工作 / 
            {settings.defaultPomodoroSettings.breakDuration}分钟休息
          </Text>
        </TouchableOpacity>
      </View>

      <View style={[styles.section, { backgroundColor: colors.card }]}>
        <Text style={[styles.sectionTitle, { color: colors.text }]}>通知设置</Text>
        <View style={styles.settingItem}>
          <Text style={[styles.settingLabel, { color: colors.text }]}>启用通知</Text>
          <Switch
            value={settings.notifications}
            onValueChange={toggleNotifications}
            trackColor={{ false: colors.border, true: colors.primary }}
            thumbColor={colors.card}
          />
        </View>
        <View style={styles.settingItem}>
          <Text style={[styles.settingLabel, { color: colors.text }]}>声音提示</Text>
          <Switch
            value={settings.soundEnabled}
            onValueChange={toggleSound}
            trackColor={{ false: colors.border, true: colors.primary }}
            thumbColor={colors.card}
          />
        </View>
      </View>

      <Modal
        visible={showPomodoroModal}
        animationType="slide"
        transparent={true}
        onRequestClose={() => setShowPomodoroModal(false)}
      >
        <View style={styles.modalContainer}>
          <View style={[styles.modalContent, { backgroundColor: colors.card }]}>
            <Text style={[styles.modalTitle, { color: colors.text }]}>番茄钟设置</Text>
            
            <View style={styles.inputGroup}>
              <Text style={[styles.inputLabel, { color: colors.text }]}>工作时长（分钟）</Text>
              <TextInput
                style={[styles.input, { 
                  borderColor: colors.border,
                  color: colors.text,
                  backgroundColor: colors.background
                }]}
                keyboardType="number-pad"
                value={tempPomodoroSettings.workDuration.toString()}
                onChangeText={(value) => setTempPomodoroSettings({
                  ...tempPomodoroSettings,
                  workDuration: parseInt(value) || 0,
                })}
              />
            </View>

            <View style={styles.inputGroup}>
              <Text style={[styles.inputLabel, { color: colors.text }]}>短休息时长（分钟）</Text>
              <TextInput
                style={[styles.input, { 
                  borderColor: colors.border,
                  color: colors.text,
                  backgroundColor: colors.background
                }]}
                keyboardType="number-pad"
                value={tempPomodoroSettings.breakDuration.toString()}
                onChangeText={(value) => setTempPomodoroSettings({
                  ...tempPomodoroSettings,
                  breakDuration: parseInt(value) || 0,
                })}
              />
            </View>

            <View style={styles.inputGroup}>
              <Text style={[styles.inputLabel, { color: colors.text }]}>长休息时长（分钟）</Text>
              <TextInput
                style={[styles.input, { 
                  borderColor: colors.border,
                  color: colors.text,
                  backgroundColor: colors.background
                }]}
                keyboardType="number-pad"
                value={tempPomodoroSettings.longBreakDuration.toString()}
                onChangeText={(value) => setTempPomodoroSettings({
                  ...tempPomodoroSettings,
                  longBreakDuration: parseInt(value) || 0,
                })}
              />
            </View>

            <View style={styles.inputGroup}>
              <Text style={[styles.inputLabel, { color: colors.text }]}>长休息间隔（番茄钟数）</Text>
              <TextInput
                style={[styles.input, { 
                  borderColor: colors.border,
                  color: colors.text,
                  backgroundColor: colors.background
                }]}
                keyboardType="number-pad"
                value={tempPomodoroSettings.longBreakInterval.toString()}
                onChangeText={(value) => setTempPomodoroSettings({
                  ...tempPomodoroSettings,
                  longBreakInterval: parseInt(value) || 0,
                })}
              />
            </View>

            <View style={styles.modalButtons}>
              <TouchableOpacity
                style={[styles.modalButton, { backgroundColor: colors.error }]}
                onPress={() => setShowPomodoroModal(false)}
              >
                <Text style={styles.modalButtonText}>取消</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[styles.modalButton, { backgroundColor: colors.primary }]}
                onPress={savePomodoroSettings}
              >
                <Text style={styles.modalButtonText}>保存</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  section: {
    marginVertical: 8,
    paddingHorizontal: 16,
    paddingVertical: 12,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '600',
    marginBottom: 12,
  },
  settingItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 12,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  settingLabel: {
    fontSize: 16,
  },
  settingValue: {
    fontSize: 14,
  },
  themeButtons: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  themeButton: {
    flex: 1,
    paddingVertical: 8,
    paddingHorizontal: 12,
    borderRadius: 8,
    marginHorizontal: 4,
    alignItems: 'center',
  },
  themeButtonText: {
    fontSize: 14,
  },
  modalContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
  },
  modalContent: {
    borderRadius: 12,
    padding: 20,
    width: '90%',
    maxHeight: '80%',
  },
  modalTitle: {
    fontSize: 20,
    fontWeight: '600',
    marginBottom: 16,
    textAlign: 'center',
  },
  inputGroup: {
    marginBottom: 16,
  },
  inputLabel: {
    fontSize: 16,
    marginBottom: 8,
  },
  input: {
    borderWidth: 1,
    borderRadius: 8,
    padding: 12,
    fontSize: 16,
  },
  modalButtons: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 20,
  },
  modalButton: {
    flex: 1,
    padding: 14,
    borderRadius: 8,
    marginHorizontal: 8,
  },
  modalButtonText: {
    color: 'white',
    textAlign: 'center',
    fontSize: 16,
    fontWeight: '600',
  },
});

export default SettingsScreen; 